var readline = require('readline');
/* 引入net模块 */
var net = require("net");

/* 创建TCP客户端 */
var client = net.Socket();
/* 监听服务器传来的data数据 */
client.on("data", function (data) {
   console.log(data.toString());
   // console.log(data);
})

/* 监听end事件 */
client.on("end", function () {
   console.log("remote closed");
 
})

client.on('error',(err)=>{
});

var rl = readline.createInterface(process.stdin,process.stdout);
rl.setPrompt('> ');
rl.prompt();

var isconnect = false;

rl.on('line',(line)=>{
  switch(line.trim()){
    case 'connect':
      client.connect(4001, '127.0.0.1', function () {
         console.log("connected the server");
         isconnect = true;
    })
      break;
    case 'exit':
    {
        process.exit(0);
    }break;
    default:
        if (isconnect) {
      //console.log(line);
      client.write(JSON.stringify({
          msgtype:"command",
          command:line
      }));
        } else {
            console.log("please connect server first");
        }
      break;
  }
  rl.prompt();
});

rl.on('close',function(){
  console.log('welcome');
  process.exit(0);
});
rl.on('pause', function() {
  console.log('Readline pause.');
});